package com.hanhanxiaochong.zhongxiangchuanmei.view.order.act;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ProductEvaluationBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ProjectEvaluationBean;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.EvaluationPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.DensityUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ToastUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.glide.GifSizeFilter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.glide.GlideImgManager;
import com.hanhanxiaochong.zhongxiangchuanmei.util.glide.MyGlideEngine;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IEvaluationView;
import com.hanhanxiaochong.zhongxiangchuanmei.view.order.adapter.EvaluationAdapter;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.StarBar;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.WrapLinearLayout;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.RetrofitSource;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.utils.FileProviderUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author : 贾桐
 * E-mail : 653773284@qq.com
 * Time   : 2018/5/8.
 * Desc   : 订单待评价act
 */

public class OrderWaitCommentActivity extends BaseActivity<EvaluationPresenter> implements IEvaluationView {

    @BindView(R.id.img_left)
    ImageView imgLeft;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.rv_order_evaluate)
    RecyclerView rvOrderEvaluate;
    @BindView(R.id.txt_comment)
    TextView txtComment;

    private static final int REQUEST_CODE_CHOOSE = 0x01;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_order_num)
    TextView tvOrderNum;
    @BindView(R.id.iv_good_pic)
    ImageView ivGoodPic;
    @BindView(R.id.iv_self_support)
    ImageView ivSelfSupport;
    @BindView(R.id.tv_good_name)
    TextView tvGoodName;
    @BindView(R.id.tv_project_fit)
    TextView tvProjectFit;
    @BindView(R.id.tv_vip_price)
    TextView tvVipPrice;
    @BindView(R.id.tv_normal_price)
    TextView tvNormalPrice;
    @BindView(R.id.tv_project_time)
    TextView tvProjectTime;
    @BindView(R.id.star_project)
    StarBar starProject;
    @BindView(R.id.tv_score_project)
    TextView tvScoreProject;
    @BindView(R.id.star_service)
    StarBar starService;
    @BindView(R.id.tv_score_service)
    TextView tvScoreService;
    @BindView(R.id.star_shop)
    StarBar starShop;
    @BindView(R.id.tv_score_shop)
    TextView tvScoreShop;
    @BindView(R.id.et_evaluation_content)
    EditText etEvaluationContent;
    @BindView(R.id.iv_choose_pic)
    ImageView ivChoosePic;
    @BindView(R.id.ll_evaluation_pic_container)
    WrapLinearLayout llEvaluationPicContainer;
    @BindView(R.id.ll_item_order_evaluation)
    LinearLayout llItemOrderEvaluation;
    @BindView(R.id.sv_project_evaluation)
    ScrollView scrollView;

    private String token;
    private EvaluationAdapter evaluationAdapter;
    private List<ProductEvaluationBean.StoreBean.ProductBean> list;
    //项目评价"project",商品评价"product"
    private String type;
    //项目评价图片url集合
    private List<String> projectPicUrls = new ArrayList<>();
    private StringBuilder projectPic = new StringBuilder();
    private String projectOrderNum;
    private String projectOrderId;
    private String projectId;
    private String scoreProject;
    private String scoreService;
    private String scoreShop;
    private String productOrderNum;

    public static Intent createIntent(Context context, String type, String order_id) {
        Intent intent = new Intent(context, OrderWaitCommentActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("order_id", order_id);
        return intent;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_order_wait_comment);
    }

    @Override
    protected void initPresenter() {
        mPresenter = new EvaluationPresenter(this);
    }

    @Override
    protected void init() {
        token = SharedPreferencesUtil.getsInstances(this).getLoginInfo().getToken();
        type = getIntent().getStringExtra("type");
        String order_id = getIntent().getStringExtra("order_id");
        if (type.equals("project")) {
            scrollView.setVisibility(View.VISIBLE);
            rvOrderEvaluate.setVisibility(View.GONE);
            mPresenter.getProjectEvaluationDetail(token, order_id);
        } else {
            scrollView.setVisibility(View.GONE);
            rvOrderEvaluate.setVisibility(View.VISIBLE);
            mPresenter.getProductEvaluationDetail(token, order_id);
        }
        setTopView();
        setRecyclerView();
    }

    private void setRecyclerView() {
        rvOrderEvaluate.setLayoutManager(new LinearLayoutManager(this));
        list = new ArrayList<>();
        evaluationAdapter = new EvaluationAdapter(this, R.layout.item_order_evaluation, list, "");
    }

    private void setTopView() {
        imgLeft.setImageResource(R.mipmap.icon_left);
        txtTitle.setText("待评价");
    }

    @OnClick({R.id.ll_leftview, R.id.txt_comment, R.id.iv_choose_pic})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.ll_leftview:
                finish();
                break;
            case R.id.iv_choose_pic:
                Matisse.from(OrderWaitCommentActivity.this)
                        .choose(MimeType.allOf())
                        .countable(true)
                        .maxSelectable(6)
                        .captureStrategy(new CaptureStrategy(true, FileProviderUtils.getFileProviderName(mContext)))
                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                        .gridExpectedSize(mContext.getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(new MyGlideEngine())
                        .forResult(REQUEST_CODE_CHOOSE);
                break;
            case R.id.txt_comment:
                if (type.equals("project")) {
                    for (int i = 0; i < projectPicUrls.size(); i++) {
                        if (i != projectPicUrls.size() - 1) {
                            projectPic.append(projectPicUrls.get(i)).append(",");
                        } else {
                            projectPic.append(projectPicUrls.get(i));
                        }
                    }
                    mPresenter.commitProjectEvaluation(token, projectOrderNum, projectId, projectOrderId, scoreProject, scoreShop, scoreService,
                            TextUtils.isEmpty(etEvaluationContent.getText().toString()) ? "用户未提交评价内容" : etEvaluationContent.getText().toString(),
                            projectPic.toString());
                } else {
                    mPresenter.commitProductEvaluation(token,
                            productOrderNum, evaluationAdapter.getProductIdList(), evaluationAdapter.getShopIdList(),
                            evaluationAdapter.getProductScoreList(), evaluationAdapter.getShopScoreList(), evaluationAdapter.getServiceScoreList(),
                            evaluationAdapter.getEvaluationContentList(), evaluationAdapter.getAllPicUrls());
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> uris = Matisse.obtainResult(data);
            List<String> paths = new ArrayList<>();
            for (Uri uri : uris) {
                String filePath = FileProviderUtils.getRealPathFromURI(this, uri);
                paths.add(filePath);
            }
            mPresenter.uploadPic(token, paths);
        }
    }

    @Override
    public void uploadSuccess(List<String> urls) {
        if (type.equals("project")) {
            for (String url : urls) {
                View picView = ResourcesUtils.inflate(R.layout.cl_evaluation_pic);
                ImageView pic = picView.findViewById(R.id.iv_evaluation_pic);
                ImageView deletePic = picView.findViewById(R.id.iv_delete_pic);
                GlideImgManager.glideLoader(mContext, RetrofitSource.image_url + url, R.mipmap.img_error, R.mipmap.img_error, pic);
                deletePic.setOnClickListener(view -> {
                    llEvaluationPicContainer.removeView(picView);
                    projectPicUrls.remove(url);
                });
                llEvaluationPicContainer.addView(picView);
                ViewGroup.LayoutParams layoutParams = picView.getLayoutParams();
                layoutParams.width = DensityUtil.dip2px(90, this);
                layoutParams.height = DensityUtil.dip2px(90, this);
                picView.requestLayout();
            }
            projectPicUrls.addAll(urls);
        } else {
            evaluationAdapter.getUploadPic(urls);
        }
    }

    @Override
    public void setProductEvaluationDetail(ProductEvaluationBean data) {
        productOrderNum = data.getOrder_num();
        for (ProductEvaluationBean.StoreBean storeBean : data.getStore()) {
            list.addAll(storeBean.getProduct());
        }
        evaluationAdapter = new EvaluationAdapter(this, R.layout.item_order_evaluation, list, productOrderNum);
        rvOrderEvaluate.setAdapter(evaluationAdapter);
    }

    @Override
    public void setProjectEvaluationDetail(ProjectEvaluationBean data) {
        ProjectEvaluationBean.ProjectBean projectBean = data.getProject();
        projectOrderNum = data.getOrder_num();
        projectOrderId = data.getId();
        projectId = projectBean.getId();
        scoreProject = "5";
        scoreService = "5";
        scoreShop = "5";
        GlideImgManager.glideLoader(mContext, RetrofitSource.image_url + projectBean.getPic().split(",")[0], R.mipmap.img_error, R.mipmap.img_error, ivGoodPic);
        tvGoodName.setText(projectBean.getP_name());
        ivSelfSupport.setVisibility(projectBean.getSelf_support().equals("y") ? View.VISIBLE : View.GONE);
        tvVipPrice.setText(String.format(ResourcesUtils.getString(R.string.vip_good_price), projectBean.getPrice_vip()));
        tvNormalPrice.setText(String.format(ResourcesUtils.getString(R.string.normal_good_price), data.getPrice()));
        starProject.setIntegerMark(true);
        starService.setIntegerMark(true);
        starShop.setIntegerMark(true);
        starProject.setOnStarChangeListener(mark -> {
            tvScoreProject.setText(String.format(ResourcesUtils.getString(R.string.score), String.valueOf(mark)));
        });
        starService.setOnStarChangeListener(mark -> {
            tvScoreService.setText(String.format(ResourcesUtils.getString(R.string.score), String.valueOf(mark)));
        });
        starShop.setOnStarChangeListener(mark -> {
            tvScoreShop.setText(String.format(ResourcesUtils.getString(R.string.score), String.valueOf(mark)));
        });
        tvShopName.setText(projectBean.getS_id() == null ? "总店" : projectBean.getS_name());
        tvOrderNum.setText(data.getOrder_num());
    }

    @Override
    public void commitSuccess(String data) {
        ToastUtils.showToast(data);
        finish();
    }
}
